<template>
  <!-- 添加或修改入库单对话框 -->
  <el-dialog :title="title" :visible.sync="open" width="90%" append-to-body :close-on-click-modal="false" v-dialogDrag>
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="类型" prop="type">
            <el-radio-group v-model="form.type" disabled>
              <el-radio v-for="dict in dict.type.churuku_type" :key="dict.value" :label="dict.value">{{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="form.type === '0'">
          <el-form-item label="入库人" prop="rukupeople">
            <el-input v-model="form.rukupeople" placeholder="请输入入库人" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="form.type === '1'">
          <el-form-item label="出库人" prop="rukupeople">
            <el-input v-model="form.rukupeople" placeholder="请输入出库人" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="form.type === '0'">
          <el-form-item label="入库日期" prop="rukuDate">
            <el-date-picker clearable v-model="form.rukuDate" type="datetime" value-format="yyyy-MM-dd"
              placeholder="请选择入库日期">
            </el-date-picker>
          </el-form-item>
        </el-col>

        <el-col :span="12" v-if="form.type === '1'">
          <el-form-item label="出库日期" prop="rukuDate">
            <el-date-picker clearable v-model="form.rukuDate" type="datetime" value-format="yyyy-MM-dd"
              placeholder="请选择出库日期">
            </el-date-picker>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="供应商:" prop="supplierId">
            <el-select v-model="form.supplierId" placeholder="请选择供应商" filterable remote reserve-keyword
              :remote-method="searchSupplier" :loading="loadingSupplier" style="width: 300px;">
              <el-option v-for="item in optionsSupplier" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12" v-if="form.type === '1'">
          <el-form-item label="领料人" prop="picker">
            <el-input v-model="form.picker" placeholder="请输入领料人" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="订单编号" prop="projectNo">
            <el-select v-model="projectNos" multiple filterable remote reserve-keyword placeholder="请输入订单编号"
              :remote-method="search" :loading="loading3">
              <el-option v-for="item in orderList" :key="item.code" :label="item.code" :value="item.code">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input type="textarea" v-model="form.remark" placeholder="请输入备注" />
          </el-form-item>
        </el-col>





      </el-row>
    </el-form>

    <el-table border v-loading="loading" :data="dataList" @selection-change="handleSelectionChange" ref="table"
      :max-height="tableMaxHeight" @sort-change="handleSortChange">
      <!--序号 默认是index 可以修改-->
      <el-table-column prop="sort" label="序号" width="150">
        <template slot-scope="scope">
          <el-input-number size="mini" v-model="scope.row.sort"></el-input-number>
        </template>
      </el-table-column>

      <el-table-column prop="goodsBrand" label="物料选择" width="380">
        <template slot-scope="scope">
          <el-autocomplete style="width: 350px;" v-model="scope.row.goodsBrand" :fetch-suggestions="querySearch"
            placeholder="请输入内容">
            <template #default="{ item, index }">
              <div @click="handleClick(item, scope.$index)">
                {{ item.value }}
              </div>
            </template>
          </el-autocomplete>
        </template>
      </el-table-column>
      <el-table-column prop="code" label="存货编码" />
      <el-table-column prop="goodsName" label="物料名称" />
      <el-table-column prop="goodModel" label="物料型号" />
      <el-table-column prop="goodUnit" label="单位" />
      <el-table-column prop="count" label="库存数量" />
      <el-table-column prop="unit" label="单位" />
      <el-table-column label="数量/重量" align="center" key="status">
        <template slot-scope="scope">
          <el-switch @change="updateTotalCost(scope.row)" v-model="scope.row.goodsType" active-value="1"
            inactive-value="0"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="请购/自制" align="center" key="isdo">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.isdo" active-value="1" inactive-value="0"></el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="daohuoCount" label="产品数量" width="150">
        <template slot-scope="scope">
          <el-input-number size="mini" @change="updateTotalCost(scope.row)"
            v-model="scope.row.daohuoCount"></el-input-number>
        </template>
      </el-table-column>
      <el-table-column prop="dun" label="重量" width="150">
        <template slot-scope="scope">
          <el-input-number size="mini" v-model="scope.row.dun" @change="updateTotalCost(scope.row)"></el-input-number>
        </template>
      </el-table-column>
      <el-table-column prop="goodsBuyPrice" label="单价" width="150">
        <template slot-scope="scope">
          <el-input-number size="mini" v-model="scope.row.goodsBuyPrice"
            @change="updateTotalCost(scope.row)"></el-input-number>
        </template>
      </el-table-column>
      <el-table-column prop="goodsBuyTotal" label="总价" width="150">
        <template slot-scope="scope">
          <el-input-number size="mini" v-model="scope.row.goodsBuyTotal"></el-input-number>
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" width="150">
        <template slot-scope="scope">
          <el-input size="mini" v-model="scope.row.remark"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="220">
        <template slot-scope="scope">
          <el-popconfirm :title="`确认删除当前数据项？`" @confirm="handleDelete(scope.row, scope.$index)"
            style="margin-left: 10px;">
            <el-button slot="reference" size="mini" type="text" icon="el-icon-delete"
              v-hasPermi="['develop:GoodsSaleMaterial:remove']">删除
            </el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-row>
      <el-col :span="24" style="text-align: center;padding-top: 20px;">
        <el-button style="width: 100%;" icon="el-icon-plus" plain type="primary" @click="addRow">添加行</el-button>
      </el-col>
    </el-row>
    <div slot="footer" class="dialog-footer">
      <el-button @click="TSBnt">暂存 数据</el-button>
      <el-button type="primary" @click="submitForm">确 定 入/出 库</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addAction, deleteAction, getAction, getById, updateAction, isEmpty, accMul } from '@/api/manage';
import moment from 'moment';

export default {
  name: "LvRukuOtherListForm",
  dicts: ['churuku_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      activeName: "first",
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      type: null,
      loadingSupplier: false,
      optionsSupplier: [],
      dataList: [],
      orderList: [],
      projectNos: [],
      loading3: false,
      goodsList: [],
      queryParams: {
        orderByColumn: "a.sort",
        isAsc: "asc",
        parentId: null,
        pageSizeZero: true,
      },
      goodsQueryParams: {
        name: null,
        pageNum: 1,
        pageSize: 20,
      },
      // 表单校验
      rules: {
        type: [{ required: true, message: "请选择出入库类别", trigger: "change" }],
        rukupeople: [{ required: true, message: "入库人不能为空", trigger: "change" }],
        rukuDate: [{ required: true, message: "请选择出入库日期", trigger: "change" }],
      },
      tableMaxHeight: window.innerHeight - 320,
      url: {
        getById: '/lvRuku/lvRuku/',
        add: '/lvRuku/lvRuku/addWithDetail',
        edit: '/lvRuku/lvRuku/editWithDetail',
        detailList: '/lvRukumingxi/lvRukumingxi/list',
        remove: '/lvRukumingxi/lvRukumingxi/removeDetail/',
      },
    };
  },
  created() {

  },
  methods: {

    updateTotalCost(row) {
      let that = this;
      if (row.goodsType === "0") {
        if (row.daohuoCount && row.goodsBuyPrice) {
          let totleCost = accMul(row.daohuoCount, row.goodsBuyPrice);
          that.$set(row, "goodsBuyTotal", totleCost);
        }
      }
      if (row.goodsType === "1") {
        if (row.dun && row.goodsBuyPrice) {
          let totleCost = accMul(row.dun, row.goodsBuyPrice);
          that.$set(row, "goodsBuyTotal", totleCost);
        }
      }
    },
    async search(queryString) {
      this.loading3 = true;
      if (queryString) {
        try {
          let params = {
            // "pageSizeZero": true,
            "pageNum": 1,
            "pageSize": 20,
            "code": queryString

          };
          getAction("/projectBaseInfo/projectBaseInfo/list", params).then(response => {
            this.orderList = response.rows;
            this.loading3 = false;
          });

        } catch (error) {
          console.error('Error fetching data:', error);
          this.loading3 = false;
        }
      } else {
        this.orderList = [];
        this.loading3 = false;
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        code: null,
        name: null,
        mainId: null,
        nos: null,
        ddDate: null,
        subDate: null,
        type: null,
        source: "2",
        ywType: null,
        customerId: null,
        customerName: null,
        isBuy: null,
        money: null,
        counts: null,
        dunwei: null,
        supplierId: null,
        supplierName: null,
        deptId: null,
        deptName: null,
        userId: null,
        userName: null,
        state: null,
        rukupeople: this.$store.getters.nickName,
        rukuid: this.$store.getters.userId,
        rukuDate: new Date(),
        status: "1",
        isdo: "0",
      };
      this.resetForm("form");
    },
    // 暂存数据
    TSBnt() {
      localStorage.setItem("ruKuForm", JSON.stringify(this.form));
      localStorage.setItem("ruKuList", JSON.stringify(this.dataList));
      this.$modal.$attrs('暂存成功')
     },
    /** 新增按钮操作 */
    handleAdd(type) {
      if (JSON.parse(localStorage.getItem("ruKuList")) || JSON.parse(localStorage.getItem("ruKuForm"))) {
        this.form = JSON.parse(localStorage.getItem("ruKuForm"))
        this.dataList = JSON.parse(localStorage.getItem("ruKuList"))
        this.title = this.form.type == 1 ? "添加出库单" : "添加入库单";
        this.open = true;
        this.loading = false;
      } else {
        this.reset();
        this.form.type = type;
        this.open = true;
        this.title = type == 1 ? "添加出库单" : "添加入库单";
        this.dataList = [];
        for (let i = 0; i < 1; i++) {
          this.dataList.push({
            isdo: '0',
            goodsType: '0',//产品类别
            sort: 1,//产品编号
            goodsId: '',//产品编号
            goodsCode: '',//产品编号
            goodsName: '',//名称
            unit: '', //产品单位
            goodModel: '',
            daohuoCount: 0,
            dun: 0,
            remark: '',//备注
          })
        }
        this.loading = false;
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      this.type = row.type;
      this.title = "修改" + (row.type === '0' ? '入' : '出') + "库单";
      this.queryParams.parentId = row.id;
      this.getList();
      getById(this.url.getById, id).then(response => {
        this.form = response.data;
        this.open = true;

      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 排序触发事件 */
    handleSortChange(column, prop, order) {
      this.queryParams.orderByColumn = column.prop;
      this.queryParams.isAsc = column.order;
      this.handleQuery();
    },


    getGoodsList() {
      let params = { "pageNum": 1, "pageSize": 20, };
      getAction('/goodsOrderIn/goodsOrderIn/list', params).then(response => {
        this.goodsList = response.rows;
        for (let i = 0; i < this.goodsList.length; i++) {
          // this.goodsList[i].label = this.goodsList[i].name + '-' + this.goodsList[i].model + '-' + this.goodsList[i].code;
          this.goodsList[i].value = this.goodsList[i].name + '-' + this.goodsList[i].model + '-' + this.goodsList[i].code;
        }
      })
    },

    handleClick(item, index) {
      this.$nextTick(() => {
        let newItem = {
          sort: index + 1,
          goodsId: item.id,
          code: item.code, //产品编号
          goodsName: item.name, //名称
          goodModel: item.model,//型号
          goodsUnit: item.unit,
          goodsBrand: item.brand,
          goodsType: '0',
          isdo: '0',
          count: item.count, // 单位
          unit: item.unit, //产品单位
          daohuoCount: 0,
          dun: 0,
          goodsBuyPrice: 0,
          goodsBuyTotal: 0,
          remark: '',//备注
        }
        this.$set(this.dataList, index, newItem)
      })
    },

    /** 查询销售信息管理列表 */
    getList() {
      this.loading = true;
      getAction(this.url.detailList, this.queryParams).then(response => {
        this.dataList = response.rows;
        this.loading = false;
        if (this.dataList.length === 0) {
          for (let i = 0; i < 1; i++) {
            this.dataList.push({
              goodsType: '0',//产品类型
              isdo: '0',
              sort: "1",
              goodsId: '',//产品编号
              code: '',//产品编号
              goodsName: '',//名称
              goodModel: '',
              daohuoCount: 0,
              dun: 0,
            })
          }
        } else {
          for (let i = 0; i < this.dataList.length; i++) {
            this.dataList[i].goodsId = this.dataList[i].goodsId;
            this.dataList[i].code = this.dataList[i].code; //产品编号
            this.dataList[i].goodsName = this.dataList[i].params.goodsName; //名称
            this.dataList[i].goodModel = this.dataList[i].params.goodsModel;//型号
            this.dataList[i].goodsUnit = this.dataList[i].params.goodsUnit; // 单位
            this.dataList[i].count = this.dataList[i].params.count; // 库存数量
            this.dataList[i].goodsBrand = this.dataList[i].goodsName + '-' + this.dataList[i].goodModel + '-' + this.dataList[i].code;
          }
        }

      });
    },

    querySearch(queryLabel, cb) {
      let that = this;
      that.goodsQueryParams.queryLabel = queryLabel;

      getAction('/goodsOrderIn/goodsOrderIn/list', that.goodsQueryParams).then(response => {
        that.goodsList = response.rows;
        for (let i = 0; i < this.goodsList.length; i++) {
          that.goodsList[i].value = that.goodsList[i].name + '-' + that.goodsList[i].model + '-' + that.goodsList[i].code;
        }
        const goodsList = that.goodsList;
        const results = queryLabel
          ? goodsList.filter(that.createFilter(queryLabel))
          : goodsList;
        // 调用 callback 返回建议列表的数据
        cb(results);
      })
    },
    createFilter(queryLabel) {
      return (restaurant) => {
        return (
          restaurant.value.toLowerCase().includes(queryLabel.toLowerCase())
        );
      };
    },
    //点击按钮添加空行
    addRow() {
      this.$nextTick(() => {
        this.dataList.push({
          sort: this.dataList.length + 1,
          code: '',//产品编号
          goodsName: '',//名称
          goodModel: '',
          daohuoCount: 0,
          dun: 0,
        })
      })
    },

    /** 提交按钮 */
    submitForm() {
      let arrays = this.dataList;
      for (let i = 0; i < arrays.length; i++) {
        if (arrays[i].daohuoCount === 0) {
          this.$modal.msgError(arrays[i].goodsName + "数量不能为0");
          return;
        }
        if (arrays[i].goodsBuyPrice === 0) {
          this.$modal.msgError(arrays[i].goodsName + "单价不能为0");
          return;
        }
        if (arrays[i].goodsBuyTotal === 0) {
          this.$modal.msgError(arrays[i].goodsName + "总价不能为0");
          return;
        }
        if (isEmpty(arrays[i].goodsId)) {
          this.$modal.msgError("序号：" + i + "请选择产品");
          return;
        }
      }
      this.form.detailList = this.dataList;
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateAction(this.url.edit, this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.$emit('ok');
            });
          } else {
            addAction(this.url.add, this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              localStorage.removeItem("ruKuForm");
              localStorage.removeItem("ruKuList");
              this.open = false;
              this.$emit('ok');
            });
          }
        }
      });
    },

    handleDelete(row, index) {
      const ids = row.id || this.ids;
      if (isEmpty(ids)) {
        this.$nextTick(() => {
          this.dataList.splice(index, 1)
        })
      } else {
        deleteAction(this.url.remove, ids).then(response => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      }
    },


    async searchSupplier(queryString) {
      this.loadingSupplier = true;
      if (queryString) {
        let params = {
          "pageNum": 1,
          "pageSize": 20,
          "name": queryString
        };
        getAction("/goodsSupplier/goodsSupplier/list", params).then(response => {
          this.optionsSupplier = response.rows;
          this.loadingSupplier = false;
        });
      } else {
        this.optionsSupplier = [];
        this.loadingSupplier = false;
      }
    },


  }
};
</script>
